package com.fenghongzhang.day014;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

public class Main2Activity extends AppCompatActivity {

    private static final String TAG = "Main2Activity";
    private Intent intent;
    private MyService.MyBinder binder;
    private ServiceConnection serviceConnection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }

    public void start(View view) {
        //开启
        intent = new Intent(this, MyService.class);
        startService(intent);

    }

    public void stop(View view) {
        stopService(intent);
    }


    public void bind(View view) {
        //可以调用服务中的方法
        Intent intent = new Intent(this, MyService.class);
         serviceConnection = new ServiceConnection() {
            /**
             * 服务连接的时候调用
             * @param name
             * @param service
             */
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Log.i(TAG, "onServiceConnected: ");
                binder = (MyService.MyBinder) service;
                binder.callShow();
                //
            }

            /**
             * 非正常断开
             * 服务断开的时候调用?
             * @param name
             */
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.i(TAG, "onServiceDisconnected: ");
                //回收对象
            }
        };
        bindService(intent,serviceConnection,BIND_AUTO_CREATE);
    }


//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        if(serviceConnection != null){
//            unbindService(serviceConnection);
//        }
//    }

    public void unbind(View view) {
        unbindService(serviceConnection);
    }

    public void show2(View view) {
        binder.callShow2();
    }
}
